package com.wujunshen.designpattern.creational.singleton;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * @author frank woo(吴峻申) <br>
 *     email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2021/2/16 04:02<br>
 */
@Slf4j
public class SerialAndDeSerial {
  public static final String FILE_PATH = "/Users/wujunshen/Desktop/xxx.txt";

  @SneakyThrows
  public static void main(String[] args) {
    // 懒汉式—线程不安全 false
    log.info("懒汉式—线程不安全 {}", destroySingleton(LazyNoSafeSingleton.getInstance()));

    // 懒汉式—线程安全 方法1 false
    log.info("懒汉式—线程安全 方法1 {}", destroySingleton(LazySafeSingleton1.getInstance()));

    // 懒汉式—线程安全 方法2 false
    log.info("懒汉式—线程安全 方法2 {}", destroySingleton(LazySafeSingleton2.getInstance()));

    // 饿汉式 false
    log.info("饿汉式 {}", destroySingleton(HungrySingleton.getInstance()));

    // 双检锁式 false
    log.info("双检锁式 {}", destroySingleton(LazyDoubleCheckSingleton.getInstance()));

    // 登记式 false
    log.info("登记式 {}", destroySingleton(Singleton.getInstance()));

    // 枚举 true
    log.info("枚举 {}", destroySingleton(SingletonEnum.getInstance()));
  }

  @SneakyThrows
  private static <T> boolean destroySingleton(T instance) {
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_PATH));
    oos.writeObject(instance);

    File file = new File(FILE_PATH);
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
    return instance == ois.readObject();
  }
}
